package com.qingcheng.task;

import com.qingcheng.dao.ReplyMapper;
import com.qingcheng.pojo.comment.Reply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Component
public class ReplyTask {
    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每15S加载一次
     *
     */
    @Scheduled(cron="0/15 * * * * ?")
    public void replyLogic(){
        //加载所有评论评价
        List<Reply> replyList = replyMapper.selectAll();
        /*//创建List存放信息
        Map<String, Object> map = new HashMap<String, Object>();*/
        List<String> commentIds=new ArrayList<>();//【1.2.3.4.5】
        //遍历评论评价集合
        for (Reply reply : replyList) {
           /* redis中数据格式
           map{
             key:  commentId:
             values:  List<Reply>{
                      Reply:
                      ...
             }
           }
           *
           * */
            String commentId = reply.getCommentId();
            //将这个评论ID存入集合中
            commentIds.add(commentId);
        }
        //再commentIds中去重
        List<String> commentIdList = removeDuplicate(commentIds);

        for (String commentId : commentIdList) {
            //查询数据库存入redis中
                Example example=new Example(Reply.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("commentId",commentId);
                List<Reply> replies = replyMapper.selectByExample(example);
                redisTemplate.boundHashOps("ReplyList").put(commentId,replies);
        }
    }

    /**
     * 去重方法
     * @param list
     * @return
     */
    public static List<String> removeDuplicate(List list)  {
        for  (int i= 0 ; i<list.size()-1 ; i++){
            for(int j=list.size()-1;j>i;j--){
                if  (list.get(j).equals(list.get(i))){
                    list.remove(j);
                }
            }
        }
        return list;
    }


}




